package com.bluemsun.naturallanguageprocessing.exceptionHandler;

import com.bluemsun.naturallanguageprocessing.common.ServerResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @author hucl
 * @describe 参数校验异常处理器
 */
@RestControllerAdvice
public class ParameterValidationExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ParameterValidationExceptionHandler.class);

    @ExceptionHandler({BindException.class})
    public ServerResponse BindExceptionHandler(BindException e){
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        logger.error("error:{}",e.getMessage(),e);
        return ServerResponse.createByErrorMessage(objectError.getDefaultMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ServerResponse methodArgumentNotValidException(MethodArgumentNotValidException e){
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        logger.error("error:{}",e.getMessage(),e);
        return ServerResponse.createByErrorMessage(objectError.getDefaultMessage());
    }

    @ExceptionHandler({ConstraintViolationException.class})
    public ServerResponse constraintViolationException(ConstraintViolationException e){
        logger.error("error:{}",e.getMessage(),e);
        return ServerResponse.createByErrorMessage(e.getMessage());
    }

}
